package com.gandong8.trace.tool.service.impl;

import com.gandong8.trace.tool.service.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.RedissonClient;
import org.redisson.core.RBucket;
import org.redisson.core.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service("redissonService")
public class RedissonService implements CacheService {

    @Autowired(required = false)
    private RedissonClient redissonClient;

    @Override
    public <T> T getObj(String key) {
        RBucket<T> bucket = redissonClient.getBucket(key);
        if (bucket == null) {
            return null;
        }
        return bucket.get();
    }

    @Override
    public <T> T getObj(String key, Class<T> clazz) {
        return getObj(key);
    }

    @Override
    public <T> void setObj(String key, T obj, int expiredSeconds) {
        RBucket<T> bucket = redissonClient.getBucket(key);
        bucket.set(obj, expiredSeconds, TimeUnit.SECONDS);
    }

    @Override
    public void delObj(String key) {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        bucket.delete();
    }


    @Override
    public boolean tryLock(String key, int expiredSeconds) {
        RLock rLock = redissonClient.getLock(key);
        try {
            return rLock.tryLock(1, expiredSeconds, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.warn("tryLock Exception. key:{}", key);
            return false;
        }
    }

    @Override
    public void unlock(String key) {
        RLock rLock = redissonClient.getLock(key);
        rLock.unlock();
    }
}
